// 引用方式 参考login.vue
import axios from 'axios';
import { Notification , Loading} from 'element-ui';
import Qs from "qs";

const origin = location.origin
let path = '你的服务域名';

window.SERVER_PATH = path;
axios.defaults.baseURL = window.SERVER_PATH;


let loading;       
function startLoading() {   
    loading = Loading.service({
        lock: true,
        text: '正在加载中……',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
function endLoading() {    
    loading.close()
}
let needLoadingRequestCount = 0;

export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }
}

const httpInstance = axios.create({
  responseType: 'json',
  timeout: 10000,
  params: {},
  data: {},
  toQs:false,//是否需要序列化
  headers: {},
  hideLoading:false,
  validateStatus(status) {
    return status >= 200 && status < 300;
  },
});

function responseErrorHandler(error) {
  let text = '服务器响应失败';
  const response = JSON.parse(JSON.stringify(error));
  if (response.data || response.response.data) {
    const { code, msg , result } = response.data || response.response.data;
  }
  // 如遇异常需退出登录，在此处理
  if(!response.config.hideLoading){
    Notification.error(text)
  }
}

httpInstance.interceptors.request.use((config) => {
  const configs = config;
    if(configs.method == 'post'){
      for (const key in configs.data) {
        if(configs.data[key] === ""){
            delete configs.data[key];
        }
      };
      configs.headers['Content-Type'] =  'application/x-www-form-urlencoded';
    }else{
      for (const key in configs.params) {
        if(configs.params[key] === ""){
            delete configs.params[key];
        }
      };
      configs.headers['Content-Type'] =  'application/json';
    }
  if(!configs.hideLoading){
    showFullScreenLoading();
  }
  return configs;
}, error => Promise.reject(error));

httpInstance.interceptors.response.use((response) => {
  const { status, data } = response;
  const { code, result } = data;
  tryHideFullScreenLoading()
  if (status === 200) {
    if (code === 200) {
      if(result instanceof Array){
        if(!result[0]){
          return {nodata:true} 
        }else{
          return result
        }
      }else{
        if(result){
          return result
        }else{
          return {}
        }
      }

    }
    responseErrorHandler(response);
  }
  return Promise.reject(response);
}, (error) => {

  tryHideFullScreenLoading()
  responseErrorHandler(error);
  return Promise.reject(error);
});

export const $http = {
  get: (url, params = null, config = {}) => {
    const normalizedParams = params;
    return httpInstance.get(url, {
      params: normalizedParams,
      ...config,
    });
  },
  post: (url, data = null,config = {}) => httpInstance.post(url, data, config),
};
export default {
    install(Vue) {
      Object.defineProperty(Vue.prototype, '$http', {
        value: $http,
        writable: false,
      });
    },
};